<?php

namespace app\courier\controller;

use app\logic\WeChatPay;
use app\model\CourierInfo as ModelCourierInfo;
use app\model\CommissionLog as ModelCommissionLog;
use app\model\ServerArea as ModelServerArea;
use app\model\ExpressCertification as ModelExpressCentification;
use app\model\ApplyForSettled as ModelApplyForSettled;
use app\logic\IdentityCard as LogicIdentityCard;
use app\user\logic\User as userLogicUser;
use app\model\SysSetting as ModelSysSetting;
use app\model\CourierBank as ModelBankCard;
use app\model\WithdrawLog as ModelWithdrawLog;
use app\model\CashStream as ModelCashStream;
use app\logic\WeChatPay as LogicWeChatPay;
use app\model\Feedback as ModelFeedback;
use app\model\DepositReturnLog as ModelDepositReturnLog;

use think\Db;


class Center extends Member
{
    public function _initialize()
    {
        parent::_initialize();
    }


    /*
     *快递员个人中心信息
     * URI:/courier/center.info
     */

    public function courierCenterInfo()
    {
        //快递员信息
        $field_info = "real_name,mobile,type,head_portrait,state,is_official,is_on_duty,auth_state as authState,remark,pay_password as payPassword,password";

        $where_arr_info = [
            'id' => $this->courier_id,
        ];

        $data['info'] = ModelCourierInfo::getInstance()->toFind($where_arr_info, $field_info);

        switch ($data['info']["type"]) {
            case 'free':
                $data['info']['displayType'] = "自由快递";
                break;
            case 'profession':
                $data['info']['displayType'] = "官方快递";
                break;
            default:
                break;
        }

        //个人中心快递员今日完成及今日收入
        $field_total = "count(id) as totalDeal,sum(fee) as totalFee";

        $where_arr_total = [
            'map_id' => $this->courier_id,
            'gmt_create' => array('between', array(date("Y-m-d 00:00:00"), date("Y-m-d 23:59:59"))),
            'type' => 1
        ];
        $data['total'] = ModelCommissionLog::getInstance()->toFind($where_arr_total, $field_total);
        if ($data['total']['totalFee'] == null) $data['total']['totalFee'] = '0.00';
        //判断快递员是否已经缴纳押金
        $is_pledge = ModelApplyForSettled::getInstance()->toValue(['map_id' => $this->courier_id, 'type' => 1], 'state');
        $data['info']['isPledge'] = $is_pledge;
        //判断用户是否设置过支付密码
        if (empty($data['info']['payPassword'])) {
            $data['info']['isSetPayPwd'] = 0;
        } else {
            $data['info']['isSetPayPwd'] = 1;
        }
        //判断是否设置过登录密码
        if (empty($data['info']['password'])){
            $data['info']['isSetPwd'] = 0;
        }else{
            $data['info']['isSetPwd'] = 1;
        }
        //快递公司认证驳回理由
        $dismiss = ModelExpressCentification::getInstance()->toValue(['map_id'=>$this->courier_id,'type'=>1],'remark');
        $data['info']['dismiss'] = $dismiss;//快递员官方认证驳回理由
        _returnData($data);

    }

    /*
     * 入驻申请：基础信息、设置-修改地区----期望收件地区
     * URI：/courier/courier.address.edit
     */
    public function courierCollectAddress()
    {
//        $data['prov_id'] = 1;
//        $data['prov_name'] = '省';
//        $data['city_id'] = 2;
//        $data['city_name'] ='市';
//        $data['county_id'] = 3;
//        $data['county_name'] = '区';
//        $data['street_id'] = 4;
//        $data['street_name'] = '街道';
//        $data['detail_address'] = '道山路一号';
//        $type = $this->_getContentParams('type');
//        _toValidate('id',$type,10014);
        //省份id;
        $data['prov_id'] = $this->_getContentParams('provId');
        $data['prov_name'] = userLogicUser::getInstance()->checkAreaId($data['prov_id']); //验证省份id
        _toCompare(empty($data['prov_name']), '==', true, 10009);

        //城市id;
        $data['city_id'] = $this->_getContentParams('cityId');
        $data['city_name'] = userLogicUser::getInstance()->checkAreaId($data['city_id'], $data['prov_id']); //验证城市id
        _toCompare(empty($data['city_name']), '==', true, 10009);

        //县(区)id;
        $data['county_id'] = $this->_getContentParams('countyId');
        $data['county_name'] = userLogicUser::getInstance()->checkAreaId($data['county_id'], $data['city_id']); //验证县区id
        _toCompare(empty($data['county_name']), '==', true, 10009);

        //街道id;
        $data['street_id'] = $this->_getContentParams('streetId');
        if ($data['street_id'] > 0) {
            $data['street_name'] = userLogicUser::getInstance()->checkAreaId($data['street_id'], $data['county_id']); //验证街道
            _toCompare(empty($data['street_name']), '==', true, 10009);
            $toUpdate['area_id'] = $data['street_id'];
            $res = ModelServerArea::getInstance()->checkArea($data['street_id']);

        }else{
            $toUpdate['area_id'] = $data['county_id'];
            $res = ModelServerArea::getInstance()->checkArea($data['county_id']);

        }
        //判断地区是否在服务范围之内
        if (!$res) _returnError(15016);
        $data['detail_address'] = $this->_getContentParams('address'); //详细地址;
        _toCompare(empty($data['detail_address']), '==', true, 12004);


        $toUpdate['address'] = json_encode($data);
        $where = [
            'id' => $this->courier_id,
        ];
        $toUpdate_res = ModelCourierInfo::getInstance()->toUpdate($where, $toUpdate);
        if ($toUpdate_res) _returnData();


        _returnError(10010);
    }

    /*
    * 入驻申请：基础信息、设置-修改地区----期望派件地址
    * URI：/courier/delivery.address.edit
    */
    public function courierDeliveryAddress()
    {
//        $data['prov_id'] = 1;
//        $data['prov_name'] = '省';
//        $data['city_id'] = 2;
//        $data['city_name'] ='市';
//        $data['county_id'] = 3;
//        $data['county_name'] = '区';
//        $data['street_id'] = 4;
//        $data['street_name'] = '街道';
//        $data['detail_address'] = '道山路一号';
//        $type = $this->_getContentParams('type');
//        _toValidate('id',$type,10014);
        //省份id;
        $data['prov_id'] = $this->_getContentParams('provId');
        $data['prov_name'] = userLogicUser::getInstance()->checkAreaId($data['prov_id']); //验证省份id
        _toCompare(empty($data['prov_name']), '==', true, 10009);

        //城市id;
        $data['city_id'] = $this->_getContentParams('cityId');
        $data['city_name'] = userLogicUser::getInstance()->checkAreaId($data['city_id'], $data['prov_id']); //验证城市id
        _toCompare(empty($data['city_name']), '==', true, 10009);

        //县(区)id;
        $data['county_id'] = $this->_getContentParams('countyId');
        $data['county_name'] = userLogicUser::getInstance()->checkAreaId($data['county_id'], $data['city_id']); //验证县区id
        _toCompare(empty($data['county_name']), '==', true, 10009);

        //街道id;
        $data['street_id'] = $this->_getContentParams('streetId');
        if ($data['street_id'] > 0) {
            $data['street_name'] = userLogicUser::getInstance()->checkAreaId($data['street_id'], $data['county_id']); //验证街道
            _toCompare(empty($data['street_name']), '==', true, 10009);
            $toUpdate['delivery_area_id'] = $data['street_id'];
            $res = ModelServerArea::getInstance()->checkArea($data['street_id']);
        }else{
            $toUpdate['delivery_area_id'] = $data['county_id'];
            $res = ModelServerArea::getInstance()->checkArea($data['county_id']);
        }
        //判断地区是否在服务范围之内
        if (!$res) _returnError(15016);

        $data['detail_address'] = $this->_getContentParams('address'); //详细地址;
        _toCompare(empty($data['detail_address']), '==', true, 12004);



        $toUpdate['delivery_address'] = json_encode($data);
        $where = [
            'id' => $this->courier_id,
        ];
        $toUpdate_res = ModelCourierInfo::getInstance()->toUpdate($where, $toUpdate);
        if ($toUpdate_res) _returnData();


        _returnError(10010);
    }

    /*
     * 判断实名认证状态
     * URI：/courier/auth.check
     */
    public function checkAuthState()
    {
        $authState = ModelCourierInfo::getInstance()->toFind(['id' => $this->courier_id], 'auth_state as authState,remark');
        _returnData(['authState' => $authState]);
    }

    /*
     * 实名认证
     * URI：/courier/real.submit
     *  @param :
     *  name          |  type  | null | description
     * ---------------|--------|------|-------------
     *  passport      | string | 必填  | 登录凭证
     *  idcard_front  | string | 必填  | 身份证正面
     *  idcard_back   | string | 必填  | 身份证反面
     *  real_name     | string | 必填  | 真实姓名
     *  id_number     | string | 必填  | 身份证号
     *  startTerm     | string | 必填  | 有效起始日期
     *  endTerm       | string | 必填  | 有效结束日期
     *  head_portrait | string | 必填  | 头像
     */
    public function courierRealName()
    {
//        $data['idcard_front'] = '2121asdasdf212';
//        $data['idcard_back'] = '2121a21212sdasdf212';
//        $data['real_name'] = '林浩';
//        $data['id_number'] = '350102198810055834';
//        $data['start_term'] = '2018-01-02';
//        $data['end_term'] = '2018-02-03';
//        $data['head_portrait'] = '13123dfasdfsadfsadfasdf';


        $data['idcard_front'] = $this->_getContentParams('idcard_front'); //身份证正面
        _toCompare($data['idcard_front'], '==', '', 12008);

        $data['idcard_back'] = $this->_getContentParams('idcard_back'); //身份证反面
        _toCompare($data['idcard_back'], '==', '', 12009);

        $data['real_name'] = $this->_getContentParams('real_name'); //真实姓名
        _toCompare($data['real_name'], '==', '', 12010);

        $data['id_number'] = $this->_getContentParams('id_number'); //身份证号
        _toValidate('id', $data['id_number'], 12011);

        $data['start_term'] = $this->_getContentParams('startTerm'); //有效起始日期
        _toValidate('date', $data['start_term'], 11006); //有效期验证

        $data['end_term'] = $this->_getContentParams('endTerm'); //有效结束日期
        _toValidate('date', $data['end_term'], 11006);

        $data['head_portrait'] = $this->_getContentParams('head_portrait');//头像
        _toCompare($data['head_portrait'], '==', '', 12007);

        $bool_res = LogicIdentityCard::getInstance()->aliYunCheckIdCard($data['real_name'], $data['id_number']);
        _toCompare($bool_res, '===', false, 15009);

        $data['auth_state'] = 2;
        $where['id'] = $this->courier_id;

        //修改数据
        $res = ModelCourierInfo::getInstance()->toUpdate($where, $data);

        if ($res) _returnData();
        _returnError(10010);
    }


    /**
     * 快递公司认证
     * URI：/courier/express.authentication
     */
    public function expressAuth()
    {

        $data['expressId'] = $this->_getContentParams('expressId');
        $data['express_branch'] = $this->_getContentParams('expressBranch');
        $data['job_number'] = $this->_getContentParams('jobNumber');
        $data['work_card'] = $this->_getContentParams('workCard');

        _toCompare($data['expressId'], '==', '', 15010);//请输入快递公司id
        _toCompare($data['express_branch'], '==', '', 15011);//请输入所属分部
        _toCompare($data['job_number'], '==', '', 15012);//请输入工号
        _toCompare($data['work_card'], '==', '', 15013);//请上传工牌信息
        //省份id;
        $address['prov_id'] = $this->_getContentParams('provId');
        $address['prov_name'] = userLogicUser::getInstance()->checkAreaId($address['prov_id']); //验证省份id
        _toCompare(empty($address['prov_name']), '==', true, 10009);

        //城市id;
        $address['city_id'] = $this->_getContentParams('cityId');
        $address['city_name'] = userLogicUser::getInstance()->checkAreaId($address['city_id'], $address['prov_id']); //验证城市id
        _toCompare(empty($address['city_name']), '==', true, 10009);

        //县(区)id;
        $address['county_id'] = $this->_getContentParams('countyId');
        $address['county_name'] = userLogicUser::getInstance()->checkAreaId($address['county_id'], $address['city_id']); //验证县区id
        _toCompare(empty($address['county_name']), '==', true, 10009);

        //街道id;
        $address['street_id'] = $this->_getContentParams('streetId');
        if ($address['street_id'] > 0) {
            $address['street_name'] = userLogicUser::getInstance()->checkAreaId($address['street_id'], $address['county_id']); //验证街道
            _toCompare(empty($address['street_name']), '==', true, 10009);
            $data['area_id'] = $address['street_id'];
            $res = ModelServerArea::getInstance()->checkArea($address['street_id']);

        }else{
            $data['area_id'] = $address['county_id'];
            $res = ModelServerArea::getInstance()->checkArea($address['county_id']);

        }
        //判断地区是否在服务范围之内
        if (!$res) _returnError(15016);
        $address['detail_address'] = $this->_getContentParams('detail_address'); //详细地址;
        _toCompare(empty($address['detail_address']), '==', true, 12004);

        $data['address'] = json_encode($address);
        $data['type'] = 1;
        $data['map_id'] = $this->courier_id;

        $add_res = ModelExpressCentification::getInstance()->toAdd($data);
        if (!$add_res) _returnError('10010');
        $where_arr = [
            'id' => $this->courier_id,
        ];
        $up_arr = [
            'is_official' => 2,
        ];
        $update_res = ModelCourierInfo::getInstance()->toUpdate($where_arr, $up_arr);
        if ($update_res) _returnData();
        _returnError('10010');
    }

    /*
     * 快递员取消入驻申请
     * /courier/settle.cancel
     * type:1:微信押金；2：支付宝押金
     */
    public function settleCancel()
    {
        $module = $this->_getContentParams('module');
        _toCompare($module,'!=','courier',10823);
        $info = ModelApplyForSettled::getInstance()->toFind(['map_id'=>$this->courier_id,'type'=>1]);
        if ($info['state'] == 1){
            switch ($info['settle_type']) {
                case 1://微信
                    break;
                case 2://支付宝
                    $backInfo = \app\logic\AliPay::getInstance()->alipayRefund($info['enter_number'], $info['amount'],'',$module);
                    break;
                default:
                    break;
            }
            $backInfo = json_decode($backInfo);
            if ($backInfo['code'] == 10000 && $backInfo['msg'] == 'Success'){
                $logRes = ModelApplyForSettled::getInstance()->toUpdate(['id' => $info['id']], ['state' => 0, 'amount' => 0, 'settle_type' => 0]);
                $upRes = ModelCourierInfo::getInstance()->toUpdate(['id' => $info['map_id']], ['state' => 0]);
                $addLog = ModelDepositReturnLog::getInstance()->returnLogAdd($info['enter_number'],1);
                if ($logRes && $upRes && $addLog){
                    _returnData();
                }
                _returnError(10824);
            }else{
                _returnError(10824);
            }
        }else{
            _returnError(10824);
        }



    }

    /**
     * 押金配置接口
     * URI:/courier/cashpledge.get
     */
    public function getCashPledge()
    {
        $cashPledge = ModelSysSetting::getInstance()->getValue('cash_pledge');
        _returnData(['cashPledge' => $cashPledge]);
    }
    /*
     * 入驻生成记录
     * URI：/courier.enter.record
     */
    public function createEnterRecord()
    {
        $amount = $this->_getContentParams('amount');//押金金额 or 蚂蚁积分
        _toValidate('money',$amount,11007);

        $cashPledge = ModelSysSetting::getInstance()->getValue('cash_Pledge');//获取后台设定的押金金额
        _toCompare($amount, "!=", $cashPledge, 15031);

        $recordId = ModelApplyForSettled::getInstance()->createRecord($this->courier_id,1,$amount);
        if ($recordId){
            _returnData(['recordId'=>$recordId]);
        }else{
            _returnError(10010);

        }
    }

    /*
     * 入驻提交押金或芝麻信用分认证
     * type:1:微信押金，2：支付宝押金；3：芝麻分认证
     * URI:/courier/payment.submit
     */
    public function submitPay()
    {
        $recordId = $this->_getContentParams('recordId');
        _toValidate('id',$recordId,10009);
        $type = $this->_getContentParams('type');
        $module = $this->_getContentParams('module');
        _toCompare($module,'!=','courier',10823);

        //入驻单号
        $enterInfo = ModelApplyForSettled::getInstance()->toFind(['id'=>$recordId]);
        switch ($type) {
            case 1 : //微信押金付款
//                $res = LogicWeChatPay::getInstance()->weChatAppPay('YJ20180418111111',0.01);
//                $data['describe'] = '快递员微信押金入驻';
                break;
            case 2 : //支付宝押金
                $payInfo = \app\logic\AliPay::getInstance()->aliAppPay($enterInfo['enter_number'], $enterInfo['amount'],$module);
                break;
//            case 3 : //蚂蚁积分
//                _toValidate('money', $amount, 15030);
//                _toCompare($amount, "!=", $creditScore, 15030);
////                $data['describe'] = '快递员蚂蚁积分入驻';
//                break;
            default :
                _returnError(10014);
                break;

        }
        _returnData(['payInfo'=>$payInfo]);
    }


    /*
     * 返回押金类型
     * URI：/courier/pledge.type
     */
    public function checkPledgeType()
    {
        $settleType = ModelApplyForSettled::getInstance()->toValue(['map_id' => $this->courier_id, 'type' => 1], 'settle_type as settleType');
        _returnData(['settleType' => $settleType]);
    }

    /*
     * 提现
     * URI：/courier/withdraw.submit
     */
    public function withdrawSubmit()
    {
        $bankCardId = $this->_getContentParams('bankCardId');//银行卡id

        $bankCardNumber = $this->_getContentParams('bankCardNumber'); //银行卡号

        $money = $this->_getContentParams('money');//提现金额

        _toValidate('money', $money, 11007);

        $serverCharge = $this->_getContentParams('serverCharge');//手续费

        _toValidate('money', $serverCharge, 11007);

        $obj_pay_pwd = new \app\logic\PayPassword($this->str_module_name);
        // 检查支付密码是否正确

        $bool_is_right = $obj_pay_pwd->checkPayPasswordIsRight($this->courier_id, $this->_getContentParams('payPassword'));
        _toCompare($bool_is_right, '!=', true, 10016);

        //获取系统手续费，与前台传入的手续费做比对
        $sysServerCharge = ModelSysSetting::getInstance()->getProcedureFee($money);

        _toCompare($serverCharge, '!=', $sysServerCharge, 11008); // 提现金额加上手续费不能大于账户余额

        $arr_user_info = ModelCourierInfo::getInstance()->toFind(['id' => $this->courier_id], 'balance,pay_password as payPassword,real_name as realName');
        _toCompare($money, '>', $arr_user_info['balance'] - $sysServerCharge, 11009);

        // 查找是否存在银行卡
        $bankCardInfo = ModelBankCard::getInstance()->toFind(['map_id' => $this->courier_id, 'type' => 1, 'card_number' => $bankCardNumber]);
        _toCompare(empty($bankCardInfo), '===', true, 15028);

        //相关id
        $insertId = ModelWithdrawLog::getInstance()->addWithdrawLog($this->courier_id,$bankCardId,$money,1,$bankCardNumber,$bankCardInfo['bank_name'],$arr_user_info['realName'],$serverCharge);
        if (!$insertId) _returnError(10011);
        //相关订单号
        $orderNumber = ModelWithdrawLog::getInstance()->toValue(['id'=>$insertId],'withdraw_number');
        //代付接口随机订单号
        $str_out_trade_no = $this->_getRandomString(30);

        //扣除提现金额，并写入流水
        $subtractMoney = ModelCashStream::getInstance()->editBalance(1,$this->courier_id,1,$money,'提现',$orderNumber,$insertId);
        //扣除手续费，并写入流水
        $subtractServerCharge = ModelCashStream::getInstance()->editBalance(1,$this->courier_id,1,$serverCharge,'提现手续费',$orderNumber,$insertId);

        if ($subtractMoney && $subtractServerCharge) {
            // 调用支付通道
            $obj = new \app\logic\XtPay(config('xtpay.mer_id'), config('xtpay.secret_key'));
            $bool_is_success = true;// $obj->payForBank($money, $str_out_trade_no, $arr_user_info['realName'], $bankCardInfo['card_number'], $bankCardInfo['bank_name']);
            if ($bool_is_success === true) {
                // 更新订单状态
                ModelWithdrawLog::getInstance()->toUpdate(['id' => $insertId], ['state' => 2]);
                _returnData(['recordId' => $insertId]);
            } else {
                //退回提现金额，写入余额记录表
                ModelCashStream::getInstance()->editBalance(1,$this->courier_id,0,$money,'提现金额返还',$orderNumber,$insertId);//扣除提现金额，并写入流水
                ModelCashStream::getInstance()->editBalance(1,$this->courier_id,0,$serverCharge,'提现手续费返还',$orderNumber,$insertId);//扣除手续费，并写入流水
                // 更新订单状态
                ModelWithdrawLog::getInstance()->toUpdate(['id' => $insertId], ['state' => 3]);
            }
        }
        _returnError(11011); // 提现失败请重试

    }

    /**
     * 设置登录密码(原密码)
     * URI: /courier/login.password.old.set
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function setLoginPasswordWithOldLoginPwd()
    {
        $str_login_password = $this->_getContentParams('loginPassword');
        $str_old_login_password = $this->_getContentParams('oldLoginPassword');
        $obj = new \app\logic\LoginPassword($this->str_module_name);
        $obj->setLoginPwdWithOldPwd($this->courier_id, $str_login_password, $str_old_login_password);
    }

    /**
     * 获取活动消息列表
     * URI: /courier/get.message.list
     */
    public function getMessageList()
    {
        $obj = new \app\logic\push\ClientPush($this->str_module_name);
        $int_now_page = intval($this->_getContentParams('page'));
        $int_list_rows = intval($this->_getContentParams('listRows'));
        $obj->getActivityMessageList($this->courier_id, $int_now_page, $int_list_rows);
    }

    /**
     * 获取活动消息详情
     * URI: /courier/get.message.info
     */
    public function getMessageInfo()
    {
        $str_module_name = $this->_getContentParams($this->str_module_name);
        $obj = new \app\logic\push\ClientPush($str_module_name);
        $int_message_id = $this->_getContentParams('messageId');
        $obj->getMessageInfo('activity', $int_message_id);
    }

    /**
     * 设置支付密码----手机号
     * URI:/courier/pay.password.set
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setPayPassword()
    {
        $str_pay_password = $this->_getContentParams('payPassword');
        $str_verify_code = $this->_getContentParams('code');
        $str_pass_key = $this->_getContentParams('passKey');
        $obj = new \app\logic\PayPassword($this->str_module_name);
        $obj->setUpPayPwd($this->courier_id, $str_pay_password, $str_verify_code, $str_pass_key);
    }

    /**
     * 修改支付密码   ---旧密码
     * URI：/courier/pay.pwd.set.old
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setPayPwdWithOld()
    {
        $str_pay_password = $this->_getContentParams('payPassword');
        $str_old_pay_password = $this->_getContentParams('oldPayPassword');
//        echo passwordEncryption($str_old_pay_password, $this->courier_id);die;

        $obj = new \app\logic\PayPassword($this->str_module_name);
        $obj->setPayPwdWithOldPwd($this->courier_id, $str_pay_password, $str_old_pay_password);

    }

    /**
     * 反馈 \n
     * URI : /courier.feedback.add
     * @param :
     *  name          |  type  | null | description
     * ---------------|--------|------|-------------
     *  passport      | string | 必填  | 登录凭证
     *  content       | string | 必填  | 问题内容
     *
     * @return
     *  name        |  type  | description
     * -------------|--------|-------------
     *  ----------  |------- | 无
     */
    public function addFeedback()
    {
        $data['content'] = $this->_getContentParams('content');
        _toCompare(empty($data['content']), '==', true, 13001);

        $data['map_id'] = $this->courier_id;
        $data['client'] = $this->str_module_name;
        //添加数据
        $int_feedback_id = ModelFeedBack::getInstance()->toAdd($data);

        if ($int_feedback_id > 0) _returnData();
        _returnError(10010);
    }
}
